/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.senacrs.util;

import br.com.senacrs.control.UsuarioCR;
import br.com.senacrs.model.UsuarioEN;
import br.com.senacrs.servlet.LogonServlet;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mauricio
 */
public class SecurityFilter implements Filter {

    public static final String PAGINA_LOGIN = "login.jsp";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            //String accessFile = this.getClass().getClassLoader().getResource("access.properties").getPath();
            Properties properties = new Properties();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean allowed = verifyAccess((HttpServletRequest) request);
        if (!allowed) {
            //String logon = PAGINA_LOGIN+ "?next=" + getNextURL((HttpServletRequest) request);
            String logon = PAGINA_LOGIN;
            ((HttpServletResponse) response).sendRedirect(logon);
            return;
        }
        chain.doFilter(request, response);

    }

    protected boolean verifyAccess(HttpServletRequest request) {
        //pega apenas o nome do arquivo que está sendo acessado
        String resource = request.getServletPath();
        String extensaoResource = resource.substring(resource.length() - 3);
        //se a pagina atual é a pagina de login, então não verifica o acesso
        if (("/" + PAGINA_LOGIN).equals(resource) || "css".equals(extensaoResource) ||//
                ".js".equals(extensaoResource)) {
            return true;
        }

        UsuarioEN usuarioEN = (UsuarioEN) request.getSession().getAttribute(UsuarioEN.KEY);
        
        //se não tem usuario em sessão
        if (usuarioEN == null || usuarioEN.getNome() == null) {
            if(request.getParameter(LogonServlet.USERNAME) != null){
                return true;
            }
            return false;
        }
        UsuarioCR usuarioCR = new UsuarioCR();
        //retorna true se o usuario tem as permissões para o arquivo
        return usuarioCR.hasRules(usuarioEN, resource);

    }
    //TODO revisar este metodo

    protected String getNextURL(HttpServletRequest request) {
        String url = request.getRequestURI();
        StringBuffer params = new StringBuffer("");

        Enumeration enumParams = request.getParameterNames();
        while (enumParams.hasMoreElements()) {
            String name = (String) enumParams.nextElement();
            String value = request.getParameter(name);
            if (params.length() > 0) {
                params.append("&");
            }
            params.append(name).append("=").append(value);
        }

        return url + "?" + params.toString();
    }

    @Override
    public void destroy() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}
